package cn.zl.rtsp.response;

import cn.hutool.core.util.StrUtil;
import cn.zl.rtsp.session.RTSPSession;
import cn.zl.rtsp.constant.RTSPConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public abstract class RTSPResponse {

    private static final Logger logger = LoggerFactory.getLogger(RTSPResponse.class);

    protected static final String R_N = "\r\n";
    protected static final String RTSP_OK = "RTSP/1.0 200 OK" + R_N;
    protected static final String COMMA = ",";

    protected ChannelHandlerContext context;
    protected DefaultHttpRequest request;


    protected String address = "";
    protected int cseq = -1;
    protected String transport = "";
    protected RTSPSession session;


    public RTSPResponse(ChannelHandlerContext context, DefaultHttpRequest request) {
        this.context = context;
        this.request = request;
    }

    public void decode() {
        try {
            decodeURLParam();
            decodeRTSPParam();
        } catch (Exception e) {
            logger.error("decode param error", e);
        }
    }

    /**
     * 解析URL请求参数
     **/
    public void decodeURLParam() {
        String reqUrl = request.uri();

    }

    /**
     * 解析RTSP协议属性
     **/
    public void decodeRTSPParam() {
        HttpHeaders headers = request.headers();
        this.address = request.uri();

        this.cseq = Integer.parseInt(headers.get("CSeq"));
        Channel channel = context.channel();
        this.session = channel.attr(RTSPConstant.SESSION_KEY).get();
        logger.info("session {}", this.session);


    }

    /**
     * TCP模式获取传输通道标识
     */
    public void getTCPInterleaved() {
        if (transport.contains(";")) {
            String[] str = transport.split(";");
            if (str.length >= 3) {
                String interl = str[2];
                String port = interl.split("=")[1];
//                rtpChannelId = Integer.parseInt(port.split("-")[0]);
//                rtcpChannelId = Integer.parseInt(port.split("-")[1]);
            }
        }
    }

    /**
     * UDP模式获取客户端RTP和RTCP端口
     */
    public void getUDPClientPort() {
        if (transport.contains(";")) {
            String[] str = transport.split(";");
            if (str.length >= 3) {
                String clientPort = str[2];
                String ports = clientPort.split("=")[1];
                String[] pList = ports.split("-");
                session.rtpClientPort(Integer.parseInt(pList[0]));
                session.rtcpClientPort(Integer.parseInt(pList[1]));
            }
        }
    }


    public final String response() {
        StringBuilder builder = new StringBuilder();
        builder.append(RTSP_OK);
        builder.append("CSeq: ").append(cseq).append(R_N);
        write(builder);
        builder.append(R_N);
        return builder.toString();
    }

    protected abstract void write(StringBuilder builder);

    public final void write() {
        try {
            String data = response();
            logger.info("response \n{}", data);
            byte[] bufData = data.getBytes(StandardCharsets.UTF_8);
            ByteBuf buf = UnpooledByteBufAllocator.DEFAULT.buffer(bufData.length);
            buf.writeBytes(bufData);
            context.channel().writeAndFlush(buf);
        } catch (Exception e) {
            logger.error("send error", e);
        }
    }

    public void after(){

    }

}
